package com.zzy.broker.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {
    private final int port;
    private EventLoopGroup boss;
    private EventLoopGroup worker;
    public NettyServer(int port){ this.port = port; }
    public void start() throws InterruptedException {
        boss = new NioEventLoopGroup(1);
        worker = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyServerInitializer());
        ChannelFuture f = b.bind(port).sync();
        System.out.println("MQTT server started on port " + port);
        f.channel().closeFuture().sync();
    }
    public void stop() {
        if (boss!=null) boss.shutdownGracefully();
        if (worker!=null) worker.shutdownGracefully();
    }
}
